<template lang="html">
  <div class="exam-card">
    <div class="card-header clearfix">
      <div class="time f-l">
        <i class="el-icon-time"></i>
        <!-- v-cloak避免出现{{}} -->
        <span v-cloak>倒计时：{{ hour }}:{{ min }}:{{ sec }}</span>
      </div>
      <!-- 控制答题卡显示 -->
      <div class="answer-card f-l m-l-20" @click="dialogVisible = true" id="answercard">
        <i class="el-icon-date"></i>
        <span>答题卡</span>
      </div>
      <div class="submit-paper f-r">
          <i class="el-icon-time"></i>
          <!-- v-text避免出现{{}} -->
        <span v-text="`耗时：${str}`"></span>
        <el-button id="submit" type="primary" round @click="submitPaper">交卷</el-button>
      </div>
    </div>
    <div class="card-content">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>第{{ questionId+1}}题({{questionTypeText}})</span>
          <el-button id="next"
            style="float: right; padding: 3px 0"
            type="text"
            @click="nextQuestion"
            >下一题</el-button
          >
        </div>
        <div>
          <!-- 单选 -->
          <div class="q-single" v-show="questionType == 1">
            <div class="question">
              {{ question[questionId].questionTm }}

            </div>
            <div class="answer">
              <div class="answer-item">
                  <!-- label	Radio 的 value -->
                <el-radio v-model="radio"
                 v-for="(item,index) in xuanxiang" 
	:key="index"
                 :label="index" 
                 style="width:100%"> 
                 {{item}}     
                </el-radio>
              </div>
            </div>
          </div>


        <!-- 多选 -->
            <div class="q-multiple" v-show="questionType == 3">
              <div class="question">
                 {{ question[questionId].questionTm }}
              </div>
              <div class="answer">
                
            <div class="answer-item" v-for="(item,index) in xuanxiang">
            <el-checkbox-group v-model="checked" size="small">
             <el-checkbox :label="item"  ></el-checkbox>
            </el-checkbox-group>
                </div>
              </div>
            </div>

            <!-- 判断 -->
            <div class="q-true-or-false" v-show="questionType == 4">
              <div class="question">
                {{ question[questionId].questionTm }}
              </div>
              <div class="answer">
                <div class="answer-item">
                  <el-radio v-model="radio" label="0">正确</el-radio>
                </div>
                <div class="answer-item">
                  <el-radio v-model="radio" label="1">错误</el-radio>
                </div>
              </div>
            </div>

            <!-- 填空 -->
            <div class="q-fill-in" v-show="questionType == 2">
              <div class="question">
                {{ question[questionId].questionTm }}
              </div>
              <div class="answer">
                <div class="answer-item">
                  <el-input
                    type="textarea"
                    :rows="5"
                    placeholder="请输入答案"
                    v-model="textarea">
                  </el-input>
                </div>
              </div>
            </div>

            <!-- 简答 -->
            <div class="q-short-answer" v-show="questionType == 5">
              <div class="question">
                {{ question[questionId].questionTm }}
              </div>
              <div class="answer">
                <div class="answer-item">
                  <el-input
                    type="textarea"
                    :rows="15"
                    placeholder="请输入答案"
                    v-model="textarea">
                  </el-input>
                </div>
              </div>
            </div>

            <!-- 程序 -->
            <div class="q-program" v-show="questionType == 6">
              <div class="question">
                {{ question[questionId].questionTm }}
              </div>
              <div class="answer">
                <div class="answer-item">
                  <el-input
                    type="textarea"
                    :rows="15"
                    placeholder="请输入答案"
                    v-model="textarea">
                  </el-input>
                </div>
              </div>
            </div>
          </div>

      </el-card>
    </div>
    <el-dialog title="答题卡" :visible.sync="dialogVisible" width="50%" @open="open">
      <el-button
        v-for="(item, index) in question"
        :key="index"
        :id="`list${index}`"
        :ref="`list${index}`"
        class="stu-answer-item"
        @click="clickAnswerCard(index)"
        >{{ index + 1 }}</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import { Message, MessageBox } from "element-ui";
export default {
  props: ["eid"],
  watch: {
    //监听题号变化，如果题号发生变化，则题目类型跟选项也要发送变化
    questionId(val, oldval) {
      //新值，旧值
      this.questionType = this.question[val].questionType; //修改题目类型
      //当题目类型为单选或多选时
      if (this.questionType == "1" || this.questionType == "3") {
        this.xuanxiang = this.question[val].choice; //修改当前题目下的选项
      }
    },
  },
  computed: {
    //计算题目类型
    questionTypeText() {
      switch (this.questionType) {
        case "1": //单选
          return "单选题";
        case "2": //填空
          return "填空题";
        case "3": //多选
          return "多选题";
        case "4": //判断
          return "判断题";
        case "5": //简答
          return "简答题";
        case "6": //程序
          return "程序题";
      }
    },
  },
  data() {
    return {
      dialogVisible: false, //初始化时默认不显示答题卡
      question: [{ questionTm: "" }], //添加初始值，因为axios异步,当数据没有完成加载时，会报错
      xuanxiang: [""], //接收选项值["前序遍历", "中序遍历", "后序遍历", "层序遍历"],
      transformChar: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      checked: [],
      textarea: "",
      questionType: "",
      questionId: 0,
      radio: "",
      startTime: "",
      endTime: "",
      hour: 0, //时
      min: 0, //分
      sec: 0, //秒
      timer: 0, //倒计时
      HH: 0, //时
      MM: 0, //分
      SS: 0, //秒
      timer2: 0, //耗时
      str: "",
      onblurTime: 0,
      studentAnswer: [],
      msg: "",
    };
  },
  methods: {
    //初始化试卷
    examInit() {
      let that = this; //全局函数里的this都指向window
      window.onblur = function () {
        that.onblurTime++;
        if (that.onblurTime == 3) {
          that.autoSubmitPaper();
        } else if (that.onblurTime == 1) {
          MessageBox(
            "第一次提醒:考试期间不能离开此页面哦~提醒两次，第三次离开就会直接交卷了哦",
            "提示",
            {
              confirmButtonText: "确定",
              type: "error",
            }
          );
        } else {
          MessageBox(
            "第二次提醒:考试期间不能离开此页面哦~提醒两次，第三次离开就会直接交卷了哦",
            "提示",
            {
              confirmButtonText: "确定",
              type: "error",
            }
          );
        }
      };

      //耗时
      this.timer2 = setInterval(() => {
        if (this.HH == 24) this.HH = 0;
        let str = "";
        if (++this.SS == 60) {
          if (++this.MM == 60) {
            this.HH++;
            this.MM = 0;
          }
          this.SS = 0;
        }
        str += this.HH < 10 ? "0" + this.HH : this.HH;
        str += ":";
        str += this.MM < 10 ? "0" + this.MM : this.MM;
        str += ":";
        str += this.SS < 10 ? "0" + this.SS : this.SS;
        this.str = str; //防止一直追加最后才把str赋值给this.str
      }, 1000);

      //倒计时
      this.timer = setInterval(() => {
        let timeLast = new Date(this.endTime).getTime() - new Date().getTime();
        let hour = parseInt(timeLast / (1000 * 60 * 60));
        let min = parseInt((timeLast % (1000 * 60 * 60)) / (1000 * 60));
        let sec = parseInt(
          ((timeLast % (1000 * 60 * 60)) % (1000 * 60)) / 1000
        );
        this.hour = hour < 10 ? "0" + hour : hour;
        this.min = min < 10 ? "0" + min : min;
        this.sec = sec < 10 ? "0" + sec : sec;

        if (this.hour == 0 && this.min == 0 && this.sec == 0) {
          window.clearInterval(this.timer, this.timer2);
          this.submitPaper();
        }
      }, 1000);
    },

    //保存答案
    saveAnswer(id, type) {
      switch (type) {
        case "1": //单选
        case "4": //判断
          this.studentAnswer[id].studentAnswer = this.radio; //选择的答案
          this.radio = "";
          break;
        case "3": //多选
          this.studentAnswer[id].studentAnswer = this.checked;
          // console.log(this.checked);
          this.checked = [];

          break;
        case "2": //简答
        case "5": //简答
        case "6": //程序
          this.studentAnswer[id].studentAnswer = this.textarea;
          this.textarea = "";
          break;
      }
    },
    //答案是否存在，存在则显示
    isAnswer(id) {
      //如果当前下标数组存在则
      if (this.studentAnswer[id].studentAnswer != undefined) {
        //根据题目类型判断,如果当前题目已作答则显示其答案
        switch (this.studentAnswer[id].questionType) {
          case "1":
          case "4":
            this.radio = this.studentAnswer[id].studentAnswer;
            break;
          case "3":
            this.checked = this.studentAnswer[id].studentAnswer;
            break;
          case "2":
          case "5":
          case "6":
            this.textarea = this.studentAnswer[id].studentAnswer;
            break;
        }
      }
    },
    //下一题
    nextQuestion() {
      //保存答案
      this.saveAnswer(this.questionId, this.questionType);
      // console.log(this.studentAnswer);
      if (this.questionId >= this.question.length - 1) {
        //答案存在则显示答案
        this.isAnswer(this.questionId);
        Message.success({
          showClose: true,
          message: "这是最后一题啦",
          type: "success",
        });
        return;
      } else {
        this.questionId++; //自增题目下标
        //答案存在则显示答案
        this.isAnswer(this.questionId);
      }
    },
    //submitAxios    //提交数据 传递数组
    submitAxios() {
      axios({
        method: "post",
        url: "/v1/students/studentexaminfo",
        data: qs.stringify(
          {
            //数组无法直接存入数据库，转为字符串
            studentAnswer: JSON.stringify(this.studentAnswer), //用户选择的答案
            score: "未批改",
            eid: this.eid, //试卷编号
            str: this.str, //耗时
          },
          { indices: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "交卷成功",
              type: "success",
            });
            this.$router.push("/studentHome");
            window.onblur = null;
          } else {
            Message.error({
              showClose: true,
              message: "交卷失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //自动交卷
    autoSubmitPaper() {
      this.submitAxios();
    },

    //交卷
    submitPaper() {
      //是否交卷
      this.$confirm("是否交卷?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //确定交卷
          this.submitAxios();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    open() {
      //Dialog 的内容是懒渲染的，即在第一次被打开之前，传入的默认 slot 不会被渲染到 DOM 上。
      //因此，如果需要执行 DOM 操作，或通过 ref 获取相应组件，请在 open 事件回调中进行。
      //解决Vue中使用Element 第一次打开el-dialog获取不到元素的解决办法
      // console.log(this.$refs[`list${a}`][0].$el);
      // vue中获取元素方式
      // this.$refs[`list${a}`][0].$el.classList.add("el-button--primary");
      this.$nextTick(function () {
        for (let a = 0; a < this.studentAnswer.length; a++) {
          //如果数组对应下标不为空，则把当前的答题卡题号按钮变色
          //0==""  true
          // console.log(this.studentAnswer[a].studentAnswer);
          if (
            this.studentAnswer[a].studentAnswer !== undefined &&
            this.studentAnswer[a].studentAnswer !== ""
          ) {
            document
              .querySelector(`#list${a}`)
              .classList.add("el-button--primary");
            //当题目为多选时，因为学生选择的答案为数组,当数组为长度为0时
            if (
              this.studentAnswer[a].questionType == "3" &&
              this.studentAnswer[a].studentAnswer.length == 0
            ) {
              document
                .querySelector(`#list${a}`)
                .classList.remove("el-button--primary");
            }
          }
        }
      });
    },
    //点击答题卡
    clickAnswerCard(index) {
      //切换到当前题目
      this.questionId = index;
      //关闭对话框
      this.dialogVisible = false;
      //答案存在则显示答案
      this.isAnswer(index);
    },
    //隐藏操作，隐藏交卷，下一题，答题卡
    hide() {
      this.$nextTick(() => {
        document.getElementById("next").style.display = "none";
        document.getElementById("answercard").style.display = "none";
        document.getElementById("submit").style.display = "none";
      });
    },
    //获取题目
    getQuestion() {
      axios
        .get(`/v1/students/exam/${this.eid}`)
        .then((result) => {
          if (result.data.status == 200) {
            this.question = JSON.parse(result.data.data[0].e_sj);
            this.xuanxiang = this.question[this.questionId].choice;
            this.questionType = this.question[this.questionId].questionType;
            this.studentAnswer = [...this.question];
            // console.log(this.studentAnswer);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //验证该考试是否开始和已考试
    checkEid() {
      axios
        .get(`v1/students/test/${this.eid}`)
        .then((result) => {
          // console.log(result.data);
          this.msg = result.data.msg;
          if (this.msg == "考试已结束") {
            Message.error({
              showClose: true,
              message: "考试已结束",
              type: "error",
            });
            this.hide();
          } else if (this.msg == "考试未开始") {
            Message.error({
              showClose: true,
              message: "考试未开始",
              type: "error",
            });
            this.hide();
          } else if (this.msg == "你已考试") {
            Message.error({
              showClose: true,
              message: "你已考试",
              type: "error",
            });
            this.hide();
          } else {
            //获取题目
            this.getQuestion();
            this.startTime = new Date();
            //在当前时间this.startTime变量上加上1个小时，并将结果赋值给this.endTime变量
            this.endTime = this.startTime.setHours(
              this.startTime.getHours() + 1
            );
            this.endTime = new Date(this.endTime);
            this.examInit();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  mounted() {
    //挂载阶段，发起axios请求
    //先判断该eid是否已经考试，或者未开始
    this.checkEid();
  },
  destroyed() {
    //离开当前组件就销毁
    window.onblur = null;
  },
};
</script>

<style lang="css">
[v-cloak] {
  display: none;
}
.card-header {
  padding: 10px;
  font-size: 20px;
  margin-top: 30px;
}
.answer-card {
  cursor: pointer;
}
.time,
.answer-card {
  margin-top: 10px;
}
.answer-item {
  padding: 10px;
}
.question {
  padding: 10px 0;
}
.card-content {
  width: 90%;
  margin: 0 auto;
  margin-top: 40px;
}

.card-content .box-card {
  min-height: 500px;
}

.el-button.stu-answer-item {
  margin: 10px;
  width: 60px;
  height: 60px;
}
</style>
